"""
API路由定义 - 专业RESTful设计

【优化点】
1. 精确策略控制API
2. 状态查询增强
3. 批量操作支持
4. 详细的错误处理
"""
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field
from typing import Dict, Any, List, Optional, Union
import logging
import random
import time

logger = logging.getLogger("APIRoutes")
router = APIRouter()

# ===== 数据模型 =====
class StrategyCreateRequest(BaseModel):
    """创建策略请求"""
    strategy_type: str = Field(..., description="策略类型，如 'trend', 'mean_reversion'")
    params: Dict[str, Any] = Field(default={}, description="策略参数")

class StrategyResponse(BaseModel):
    """策略响应模型"""
    strategy_id: str
    type: str
    status: str
    positions: Dict[str, float]
    params: Dict[str, Any]
    created_at: float

class BulkStopRequest(BaseModel):
    """批量停止请求"""
    strategy_ids: List[str] = Field(..., description="要停止的策略ID列表")

class MarketDataRequest(BaseModel):
    """行情数据请求"""
    symbols: List[str] = Field(default=["SH600000", "SZ000001"], description="股票代码列表")

# ===== 路由定义 =====
@router.post("/strategies", response_model=StrategyResponse, status_code=status.HTTP_201_CREATED)
async def create_strategy(request: StrategyCreateRequest):
    """创建并启动新策略"""
    try:
        from core.strategy_manager import strategy_manager
        
        # 验证策略类型
        strategy_manager.get_strategy_class(request.strategy_type)
        
        # 创建策略
        strategy_id = await strategy_manager.add_strategy(
            strategy_type=request.strategy_type,
            params=request.params
        )
        
        # 获取策略实例
        strategy = strategy_manager.get_strategy(strategy_id)
        
        return StrategyResponse(
            strategy_id=strategy_id,
            type=strategy.__class__.__name__,
            status="running",
            positions=dict(strategy.positions),
            params=strategy.params,
            created_at=strategy.created_at
        )
    
    except ValueError as e:
        logger.error(f"创建策略失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.exception("创建策略异常")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.delete("/strategies/{strategy_id}", response_model=dict)
async def stop_strategy(strategy_id: str):
    """
    【精确控制】停止指定策略 - 完全基于 strategy_id
    
    优势:
    - 不依赖 stock_code
    - 精确控制单个策略
    - 返回完整策略状态
    """
    from core.strategy_manager import strategy_manager
    
    if strategy_id not in strategy_manager._strategies:
        raise HTTPException(status_code=404, detail=f"策略不存在: {strategy_id}")
    
    result = await strategy_manager.remove_strategy(strategy_id)
    return result

@router.post("/strategies/bulk-stop", response_model=dict)
async def bulk_stop_strategies(request: BulkStopRequest):
    """
    【批量精确控制】批量停止多个策略
    
    请求示例:
    {
        "strategy_ids": ["a1b2c3d4", "e5f6g7h8"]
    }
    """
    from core.strategy_manager import strategy_manager
    
    results = {}
    
    for sid in request.strategy_ids:
        if sid in strategy_manager._strategies:
            results[sid] = await strategy_manager.remove_strategy(sid)
        else:
            results[sid] = {"status": "not_found", "error": "策略不存在"}
    
    return {
        "operation": "bulk_stop",
        "total_requested": len(request.strategy_ids),
        "successful": len([r for r in results.values() if "status" in r and r["status"] == "stopped"]),
        "results": results
    }

@router.get("/strategies", response_model=dict)
async def list_strategies(status_filter: Optional[str] = None):
    """
    查询所有策略 - 支持状态过滤
    
    查询参数:
    - status_filter: 可选，过滤状态，如 "running"
    """
    from core.strategy_manager import strategy_manager
    
    strategies = strategy_manager.list_strategies()
    
    # 应用状态过滤
    if status_filter:
        filtered = {}
        for sid, s in strategies.items():
            if status_filter == "running" and s["status"] == "running":
                filtered[sid] = s
            elif status_filter == "stopped" and s["status"] == "stopped":
                filtered[sid] = s
        strategies = filtered
    
    return {
        "total": len(strategies),
        "filter": status_filter or "all",
        "strategies": strategies
    }

@router.get("/market-data/{symbol}", response_model=dict)
async def get_market_data(symbol: str):
    """获取单个股票的行情数据 (模拟)"""
    from core.qmt_client import qmt_client
    
    try:
        data = qmt_client.get_current_data(symbol)
        return {
            "symbol": symbol,
            "data": data,
            "timestamp": data["timestamp"]
        }
    except Exception as e:
        logger.error(f"获取行情数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取行情数据失败")

@router.post("/market-data", response_model=dict)
async def get_multiple_market_data(request: MarketDataRequest):
    """获取多个股票的行情数据 (模拟)"""
    from core.qmt_client import qmt_client
    
    try:
        results = {}
        for symbol in request.symbols:
            results[symbol] = qmt_client.get_current_data(symbol)
        
        return {
            "symbols": request.symbols,
            "data": results,
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"获取多个行情数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取行情数据失败")

@router.get("/positions", response_model=dict)
async def get_positions():
    """获取当前持仓 (模拟)"""
    from core.qmt_client import qmt_client
    
    try:
        positions = qmt_client.get_stock_positions()
        return {
            "positions": positions,
            "total_value": sum(p["market_value"] for p in positions.values()),
            "timestamp": time.time()
        }
    except Exception as e:
        logger.error(f"获取持仓失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取持仓失败")

@router.post("/orders", response_model=dict)
async def place_order(
    symbol: str,
    volume: int,
    price: float = 0.0,
    order_type: str = "market"
):
    """下单接口 (模拟)"""
    from core.qmt_client import qmt_client
    
    try:
        order_id = qmt_client.order_stock(symbol, volume, price, order_type)
        return {
            "order_id": order_id,
            "status": "submitted",
            "symbol": symbol,
            "volume": volume,
            "price": price,
            "order_type": order_type
        }
    except Exception as e:
        logger.error(f"下单失败: {str(e)}")
        raise HTTPException(status_code=500, detail="下单失败")

@router.get("/system-status", response_model=dict)
async def get_system_status():
    """获取系统状态"""
    from core.strategy_manager import strategy_manager
    from core.qmt_client import qmt_client
    
    strategies = strategy_manager.list_strategies()
    running_count = sum(1 for s in strategies.values() if s["status"] == "running")
    
    return {
        "system": "quant-trading-system",
        "version": "2.0",
        "status": "running",
        "uptime": time.time() - getattr(strategy_manager, '_startup_time', time.time()),
        "strategies": {
            "total": len(strategies),
            "running": running_count,
            "stopped": len(strategies) - running_count
        },
        "subscriptions": len(strategy_manager._stock_subscribers),
        "timestamp": time.time()
    }